<?php

namespace App\Kuafu\Pay\Model;

use App\Kuafu\Base\Model\BaseModel;


class PayStreamMappingModel extends BaseModel
{
    protected $connection   = 'mysqlOrderAll';
    protected $table        = 'pay_stream_mappings';
    protected $primaryKey   = 'payNo';
    public    $incrementing = false;
    protected $keyType      = 'string';
    public    $timestamps   = false;

    protected $fillable = [
        'payNo',
        'shopId',
        'sysType',
        'bizId',
        'createdAt',
    ];

    /**
     * 仅添加堂食相关数据
     * @param array $data
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|void|null
     */
    public static function addData(array $data)
    {
        if (!in_array($data['sysType'], PayStreamModel::SYS_TYPE_PAY_IN_APP)) {
            return null;
        }

        $data['createdAt'] = time();
        return self::query()->create($data);
    }

    public static function getData(string $payNo)
    {
        return self::query()->where('payNo', $payNo)->first();
    }

    public static function getDataByBizId(string $bizId, string $payNo = ''): array
    {
        $mappings = PayStreamMappingModel::query()
                                         ->where('bizId', (string)$bizId)
                                         ->when($payNo, function ($query) use ($payNo) {
                                             $query->where('payNo', $payNo);
                                         })
                                         ->first();
        if (!$mappings) {
            return [
                'shopId'  => null,
                'sysType' => 0,
            ];
        }

        return [
            'shopId'  => $mappings->shopId,
            'sysType' => $mappings->sysType,
        ];
    }
}
